package com.vincce.sport.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.entity.ActivityBrand;
import com.vincce.sport.entity.Page;
import com.vincce.sport.mapper.ActivityBrandMapper;


@Controller
@RequestMapping("/brand")
public class ActivityBranController extends BaseController{
	@Resource
	private ActivityBrandMapper activityBrandMapper;
	
	
	/**
	 * 分页查询
	 * @param model
	 * @param page
	 * @param brand
	 * @return
	 */
	@RequestMapping("/brandList")
	public String queryBrandByPage(Model model,Page<ActivityBrand> page,ActivityBrand brand){
		Map<String, Object> filter = new HashMap<String, Object>();
		if(brand.getName() != null && !brand.getName().equals("")){
	            filter.put("name", brand.getName());
	    }
		
		page.setFilter(filter);
		page.setTotal(activityBrandMapper.queryActivityBrandCount(page.getFilter()));
		//page.setResult(activityBrandMapper.queryActivityBrandByPage(page));
		List<ActivityBrand> list=activityBrandMapper.queryActivityBrandByPage(page);
		
		
		
		for (ActivityBrand brand2 : list) {
			ActivityBrand brand3 = activityBrandMapper.queryCountById(brand2.getId());
			brand2.setCountTatal(brand3.getCountTatal());
			brand2.setConductTatal(brand3.getConductTatal());
			brand2.setStartTatal(brand3.getStartTatal());
			brand2.setEndTatal(brand3.getEndTatal());
		}
		page.setResult(replace(list));
		model.addAttribute("brand",brand);
		model.addAttribute("page",page);
		return "/backstage/activityBrandList";
	}
	
	
	/**
	 * 图片路径替换
	 * @param imgStorageList
	 * @return
	 */
	public List<ActivityBrand> replace(List<ActivityBrand> imgTempList){
		if(imgTempList!=null && imgTempList.size()>0){
			for(ActivityBrand itl:imgTempList){
				itl.setLogUrl(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+itl.getLogUrl(), "ori"));
			}
		}
		return imgTempList;
	}
	
	
	/**
	 * 新增和修改 
	 * @param model
	 * @param brand
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/addOrUpdateBrand")
	@ResponseBody
	public String addOrUpdateBrand(Model model,ActivityBrand brand,  
			@RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request) throws IOException{
		Long count=0L;
		
        Map<String, Object> result = new HashMap<String, Object>();
        SimpleStorageClient.StorageResult obj = new SimpleStorageClient.StorageResult(200, "");
        if(CheckUtil.isEmpty(brand.getId())){
        	if (file != null && !file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
                } else {
                    obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
                    if (obj.statusCode == 200) {
                    	
                    	String path = obj.info.replaceAll("\\\\", "/");
                    	//result.put("img", String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+path, "ori"));
                    	//result.put("imgPath", path);
                    	brand.setLogUrl(path);
                    	
                    	//
                    	brand.setStatus(2);
                    	brand.setCreateUser(getCurrentUser().getId().intValue());
                    	brand.setCreateTime(new Date());
                    	brand.setUpdateTime(new Date());
                    	brand.setUpdateUser(getCurrentUser().getId().intValue());
                    	count=activityBrandMapper.insertActivityBrand(brand);
                    	
                    }
                }
            } else{
            	result.put("msg","请选择文件!");
                result.put("suc", false);
            }
        	
        	
        }else{
        	
        	if (file != null && !file.isEmpty()) {
            	String fileName = file.getOriginalFilename();
            	String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            	if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
				}else{
					obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
	                if (obj.statusCode == 200) {
	                	String path= obj.info.replaceAll("\\\\", "/");
	                	brand.setLogUrl(path);
	                	brand.setUpdateTime(new Date());
	                	brand.setUpdateUser(getCurrentUser().getId().intValue());
	                	count = activityBrandMapper.updateActivityBrand(brand);
	                }
				}
            } else {
            	brand.setUpdateTime(new Date());
            	brand.setUpdateUser(getCurrentUser().getId().intValue());
            	count = activityBrandMapper.updateActivityBrand(brand);
            }
        }
        
        
        result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
	}
	
	
	
	/**
	 * 隐藏显示品牌
	 * @param brand
	 */
	@RequestMapping("/updateStatus")
	@ResponseBody
	public String updateStatus(ActivityBrand brand,Model model){
		Boolean flag=false;
		
		brand.setUpdateTime(new Date());
		brand.setUpdateUser(getCurrentUser().getId().intValue());
		Long count=activityBrandMapper.updateActivityBrand(brand);
		flag=count>0?true:false;
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("suc", flag);
        return JSON.toJSONString(result);
	}
	
	
	/**
	 * 根据ID删除
	 * @param model
	 * @param id
	 * @return
	 */
	
	@RequestMapping("/deleteById")
	@ResponseBody
	public String deleteById(Model model,Integer id){
		Boolean flag=false;
		Integer count=activityBrandMapper.deleteById(id);
		flag=count>0?true:false;
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("suc", flag);
        return JSON.toJSONString(result);
	}

}
